package com.gjx.clock.service

import android.annotation.SuppressLint
import android.app.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.widget.RemoteViews
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.lifecycle.ViewModelProvider
import com.gjx.clock.*
import com.gjx.clock.entity.NormalAlarmClock
import com.gjx.clock.ui.MainActivity
import com.gjx.clock.ui.AlarmActivity
import com.gjx.clock.ui.OnePxActivity
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.HashSet

class ForwardService : Service() {

    inner class MyTimerTast(val remoteViews:RemoteViews): TimerTask() {
        override fun run() {
            val recentTimes = aliveAlarmSet.values.sorted()

            val recentTime = if(recentTimes.size==0) "暂无闹钟" else TimeFormatHelper.timeFormat(recentTimes[0])

            val mainIntent = Intent(this@ForwardService, MainActivity::class.java)
            val pendingIntent = PendingIntent.getActivity(this@ForwardService, 0, mainIntent, 0)

            remoteViews.setTextViewText(R.id.notificationHint,"下次响铃时间：${recentTime}")
            val notification = NotificationCompat.Builder(this@ForwardService, "test")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("温馨提示")
                .setContentText("闹钟服务正在运行,请勿关闭此通知")
                .setContentIntent(pendingIntent)
                .setShowWhen(false)
                .setContent(remoteViews)
                .setCustomBigContentView(remoteViews)
                .build()

            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.notify(NOTIFI_ID,notification)
        }
    }


    val am by lazy {
        getSystemService(Context.ALARM_SERVICE) as AlarmManager
    }
    private val restClockDao = AppDatabase.getDatabase(ClockApplication.context).restClockDao()
    private val normalClockDao = AppDatabase.getDatabase(ClockApplication.context).normalClockDao()
    private val aliveAlarmSet = HashMap<Long,Long>()

    companion object {
        val ACTION_ADD_ONE_ALARM = "com.gjx.clock.ACTION_ADD_ONE_ALARM"
        val ACTION_CANCEL_ONE_ALARM = "com.gjx.clock.ACTION_CANCEL_ONE_ALARM"
        val NOTIFI_ID = 10010
    }

    val receiver = AlarmReceiver()
    val screenReceiver = object:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            when(intent?.action){
                Intent.ACTION_SCREEN_ON->{
                    // 关闭1像素activity
                    val finishOnePxIntent = Intent(OnePxActivity.ACTION_FINISH_ACTIVITY)
                    finishOnePxIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)  // 停滞状态的receiver也能收到
                    finishOnePxIntent.setPackage(packageName)
                    finishOnePxIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    sendBroadcast(finishOnePxIntent)
                }
                // 屏幕关闭时打开1像素activity
                Intent.ACTION_SCREEN_OFF->{
                    val onePxIntent = Intent(context,OnePxActivity::class.java)
                    onePxIntent.flags=Intent.FLAG_ACTIVITY_NEW_TASK
                    startActivity(onePxIntent)
                }
            }
        }
    }

    override fun onCreate() {

        // 动态注册广播
        receiver.registerAction(ACTION_ADD_ONE_ALARM)
        receiver.registerAction(ACTION_CANCEL_ONE_ALARM)

        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_SCREEN_ON)
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF)
        registerReceiver(screenReceiver,intentFilter)

        super.onCreate()
    }

    override fun onDestroy() {
        unregisterReceiver(receiver)
        super.onDestroy()
    }
    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        // 创建通知通道
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("test","AlarmTest", NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }

        val remoteViews = RemoteViews(packageName,R.layout.layout_notification)




        val intent1 = Intent(this,RestService::class.java)
        intent1.action = RestService.START_WORKING
        val pendingIntent1 = PendingIntent.getService(this,ClockApplication.restId.toInt(),intent1,PendingIntent.FLAG_UPDATE_CURRENT)

        val intent2 = Intent(this,RestService::class.java)
        intent2.action = RestService.STOP_WORKING
        val pendingIntent2 = PendingIntent.getService(this,ClockApplication.restId.toInt(),intent2,PendingIntent.FLAG_UPDATE_CURRENT)

        val intent3 = Intent(this,RestService::class.java)
        intent3.action = RestService.CANCEL
        val pendingIntent3 = PendingIntent.getService(this,ClockApplication.restId.toInt(),intent3,PendingIntent.FLAG_UPDATE_CURRENT)

        remoteViews.setOnClickPendingIntent(R.id.startWorking,pendingIntent1)
        remoteViews.setOnClickPendingIntent(R.id.startRest,pendingIntent2)
        remoteViews.setOnClickPendingIntent(R.id.cancelRestAlarm,pendingIntent3)


        val mainIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, mainIntent, 0)
        val notification = NotificationCompat.Builder(this, "test")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("温馨提示")
            .setContentText("闹钟服务正在运行,请勿关闭此通知")
            .setContentIntent(pendingIntent)
            .setShowWhen(false)
            .setContent(remoteViews)
            .setCustomBigContentView(remoteViews)
            .build()

        // 定时关闭
        val mTimerTask = MyTimerTast(remoteViews)
        val mTimer = Timer()
        mTimer.schedule(mTimerTask,0,1000)


        startForeground(NOTIFI_ID, notification) //开始前台服务



        return super.onStartCommand(intent, flags, startId)
    }

    private fun addOneAlarm(triggerAtMillis:Long,requestCode:Long,notify:Boolean,action:String?=null) {
        if (aliveAlarmSet.contains(requestCode)){
            return
        }
        if(notify) {
            Toast.makeText(this, "闹钟将在${TimeFormatHelper.timeFormat(triggerAtMillis)}开启", Toast.LENGTH_SHORT).show()
        }
        // 响铃的activity
        val intent = Intent(this, AlarmActivity::class.java)
        intent.putExtra("lastTime", Date().time)
        intent.putExtra("triggerAtMillis",triggerAtMillis)
        intent.putExtra("requestCode", requestCode)

        intent.putExtra("restAction",action)


        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        val pi = PendingIntent.getActivity(this, requestCode.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
        am.setExactAndAllowWhileIdle(
            AlarmManager.RTC_WAKEUP,
            triggerAtMillis,
            pi
        )
        aliveAlarmSet[requestCode] = triggerAtMillis
    }

    private fun cancelAlarm(requestCode:Long,notify:Boolean){
        if (!aliveAlarmSet.contains(requestCode)){
            return
        }
        aliveAlarmSet.remove(requestCode)
        val intent = Intent(this, AlarmActivity::class.java)
        val pi = PendingIntent.getActivity(this, requestCode.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
        am.cancel(pi)
        if(notify){
            Toast.makeText(this, "取消了闹钟", Toast.LENGTH_SHORT).show()
        }
    }


    inner class AlarmReceiver: BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when(intent!!.action){
                ACTION_ADD_ONE_ALARM->{
                    val action = intent?.extras!!.get("restAction") as String?

                    val requestCode = intent.extras?.getLong("requestCode")
                    val triggerAtMillis = intent.extras?.getLong("triggerAtMillis")
                    val notify = intent.extras?.getBoolean("notify")
                    addOneAlarm(triggerAtMillis!!,requestCode!!,notify!!,action)
                }
                ACTION_CANCEL_ONE_ALARM->{
                    val requestCode = intent.extras?.getLong("requestCode")
                    val notify = intent.extras?.getBoolean("notify")

                    cancelAlarm(requestCode!!,notify!!)
                }
            }
        }

        fun registerAction(action:String){
            val intentFilter = IntentFilter()
            intentFilter.addAction(action)
            this@ForwardService.registerReceiver(this,intentFilter)
        }
    }

}
